package com.shiyipicture.shiyipicturebackend.api.imageSearch.sub;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.shiyipicture.shiyipicturebackend.exception.BusinessException;
import com.shiyipicture.shiyipicturebackend.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class GetImagePageUrlApi {

  /**
   * 获取图片页面地址
   * @param imageUrl 图片url
   * @return 图片页面地址
   */
  public static String getImagePageUrl(String imageUrl){
    HashMap<String, Object> formData = new HashMap<>();
    formData.put("image",imageUrl);
    formData.put("tn","pc");
    formData.put("from","pc");
    formData.put("image_source","PC_UPLOAD_URL");

    //获取当前时间戳
    long upTime = System.currentTimeMillis();
    // 请求地址
    String url = "https://graph.baidu.com/upload?uptime=" + upTime;

    try {
      //发送post请求到百度接口
      HttpResponse response = HttpRequest.post(url)
        .form(formData)
        .timeout(5000)
        .execute();

      if (HttpStatus.HTTP_OK != response.getStatus()) {
        throw new BusinessException(ErrorCode.OPERATION_ERROR,"接口调用失败");
      }

      //解析返回结果
      String responseBody = response.body();
      Map<String,Object> result = JSONUtil.toBean(responseBody, Map.class);

      if (result == null || !Integer.valueOf(0).equals(result.get("status"))) {
        throw new BusinessException(ErrorCode.OPERATION_ERROR,"接口调用失败");
      }

      Map<String,Object> data = (Map<String,Object>)result.get("data");
      String rawUrl = (String) data.get("url");

      String searchResultUrl = URLUtil.decode(rawUrl, StandardCharsets.UTF_8);

      //如果url为空
      if (searchResultUrl == null) {
        throw new BusinessException(ErrorCode.OPERATION_ERROR,"未返回有效结果");
      }

      return searchResultUrl;
    } catch (BusinessException e) {
      log.error("搜索失败",e);
      throw new BusinessException(ErrorCode.OPERATION_ERROR,"搜索失败");
    }
  }
}
